import { useEffect, useState, forwardRef, useImperativeHandle, useMemo } from "react";
import { Form, Tree, message } from "antd";

import { IForm } from "@/components";
import { roleTypeMap } from "@/utils/consts";
import { useAppSelector } from "@/utils/hooks";

import type { FormItemConfig } from "@/components/FormItem";
import { RecordItem } from "../type";
import request from "@/utils/request";
import { transformTreeData } from "@/utils/util";

interface Props {
	selRecord?: RecordItem;
}

const AuthForm = forwardRef((props: Props, ref) => {
	const [form] = Form.useForm();
	const { currentEntity, userInfo } = useAppSelector(state => state.app);
	const [tenantResources, setTenantResources] = useState([]);
	const [resourceIds, setResourceIds] = useState([]);

	useEffect(() => {
		console.log(props.selRecord)
		queryTenantResources();
		if (props.selRecord) {
			queryAuthDetail();
		}
	}, [props.selRecord]);

	useImperativeHandle(ref, () => ({
		validateFields: () => {
			return form.validateFields().catch((error: any) => {
				message.warn("请完善监管授权信息");
				throw error;
			});
		}
	}));

	const queryAuthDetail = () => {
		request("tenantQueryById", { data: { tenantId: props.selRecord?.tenantId } }).then(res => {
			if (res.code === 0 && res.data) {
				form.setFieldsValue({ ...res.data });
				setResourceIds(res.data.resourceIds);
				queryTenantResources();
			}
		});
	};

	const queryTenantResources = () => {
		const data = {
			entityId: currentEntity.entityId
		};
		request("tenantManageQueryResource", { data }).then(res => {
			if (res.code === 0 && res.data) {
				form.setFieldsValue({ resourceList: res.data });
				setTenantResources((res.data));
			}
		});
	};

	const formItemsConfig: FormItemConfig[] = [
		{
			type: "tree",
			formItemProps: {
				label: "资源点权限",
				name: "menuIdList",
				valuePropName: "checkedKeys",
				trigger: "onCheck",
				rules: [{ required: true }],
				initialValue: resourceIds
			},
			childProps: {
				defaultExpandedKeys: resourceIds,
				// onCheck(checked, info) {
				//   // 是否需要携带半选的父亲节点
				// },
				treeData: tenantResources as any
			}
		}
	];

	return <IForm layout="vertical" form={form} formItemsConfig={formItemsConfig}></IForm>;
});

AuthForm.displayName = "AuthForm";

export default AuthForm;
